// 处理登录和注册的函数
const db = require('../db/index')
// 给密码加密的中间件
const bcrypt = require('bcrypt')
//导入fs处理路径
const fs = require('fs')
//完成图片上传以及账号绑定
exports.uploadavatar = (req, res) => {
    console.log(req.files);
    const account = req.query.account
    const oldname = req.files[0].filename
    //将二进制文件名转换成字符串
    const newname = Buffer.from(req.files[0].originalname, 'latin1').toString('utf-8')
    console.log(newname);

    const newFolderPath = `./public/upload/${account}`
    console.log(newFolderPath);

    if (!fs.existsSync(newFolderPath)) {
        fs.mkdirSync(newFolderPath);
    }
    fs.renameSync('./public/upload/' + oldname, newFolderPath + '/' + newname)
    const image_url = `http://127.0.0.1:8080/upload/${account}/${newname}`
    const sql = 'insert into image set ?'
    db.query(sql, { image_url, account }, (err, data) => {
        if (err) return res.dbno(err)
        const sql2 = 'update  users set image_url=? where account =?'
        db.query(sql2, [image_url, account], (err, data) => {
            if (err) {
                return res.dbno(err)
            }
            res.send({
                status: 200,
                message: '上传成功',
                data: { url: image_url }
            })
        })
    })
}
//修改用户信息
exports.upuserinfo = (req, res) => {
    const { name, sex, email, account } = req.body
    const time = new Date()
    const sel = 'update users set name=?,sex=?,email=? ,updata_time=? where account =?'
    db.query(sel, [name, sex, email, time, account], (err, data) => {
        if (err) return res.dbno(err)
        res.send({ status: 200, message: '修改成功' })
    })
}
// 修改密码
exports.setpwd = (req, res) => {
    const { account, oldpwd, newpwd } = req.body
    const sql = 'select password from users where account =?'
    db.query(sql, [account], (err, data) => {
        if (err) return res.dbno(err)
        const comparepwd = bcrypt.compareSync(oldpwd, data[0].password)
        console.log(comparepwd);
        if (!comparepwd) return res.no('原密码错误')
        const password = bcrypt.hashSync(newpwd, 10)
        const sql2 = 'update users set password =? where account=?'
        db.query(sql2,[password,account],(err,data)=>{
            if(err) return res.dbno(err)
                res.send({status:200,message:'修改密码成功'})
        })
    })
}
